package com.pi.uc.service;

import java.io.InputStream;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.pi.base.dto.file.transfer.StreamFileTransferForm;
import com.pi.base.enumerate.file.FileSource;
import com.pi.base.exception.ServiceException;
import com.pi.base.util.http.UrlBuilder;
import com.pi.base.util.transfer.windows.FileUtil;

@Service
public class UserPicService {

  @Value("${server.ftp.host}")
  private String ftpHost;
  @Value("${server.ftp.password}")
  private String ftpPass;
  @Value("${server.ftp.user}")
  private String ftpUserName;
  @Value("${server.ftp.parentFolder}")
  private String ftpParentFolder;
  @Value("${server.ftp.root}")
  private String ftpRoot;
  @Value("${server.ftp.url}")
  private String ftpUrl; 

  public String transferAvatarToLocal(MultipartFile file, FileSource fileSource, Long sourceId, Long userId) throws Exception{
    validFileSource(file);
    StreamFileTransferForm<InputStream> streamForm = new StreamFileTransferForm<>();
    streamForm.setFileSource(fileSource);
    streamForm.setFtpParentFolder(ftpParentFolder);
    streamForm.setFtpRoot(ftpRoot);
    streamForm.setIn(file.getInputStream());
    streamForm.setSourceId(sourceId);
    streamForm.setUserId(userId);
    String fileKey = FileUtil.transferToLocal(streamForm);
    String url = new UrlBuilder().build(ftpUrl).build(fileKey).toString();
    return url;
  }
  
  private void validFileSource(MultipartFile file){
    if(file.isEmpty()){
      throw new ServiceException("UC_USER.AVATAR_STREAM_IS_EMPTY");
    }
    int size = (int) file.getSize();
    if(size > 2*1024*1024){
      throw new ServiceException("UC_USER.AVATAR_OVER_MAX");
    }
  }
}
